package com.wanjia.bpsapi.service.jkmc;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wanjia.bpsapi.mapper.WjProductOfferMapper;
import com.wanjia.bpsapi.mapper.WjStoreProductMapper;
import com.wanjia.bpsapi.pojo.entity.WjProductOffer;
import com.wanjia.bpsapi.pojo.entity.WjStoreProduct;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class JkAsyncService {

    @Setter(onMethod_ = @Autowired)
    private JkService service;

    @Setter(onMethod_ = @Autowired)
    private WjStoreProductMapper storeProductMapper;

    @Setter(onMethod_ = @Autowired)
    private WjProductOfferMapper productOfferMapper;

    @Async
    public void asyncUpdateStock(Long... productIds) {
        updateStock(productIds);
    }

    public void updateStock(Long... productIds) {
        // 获取自用商品
        QueryWrapper<WjStoreProduct> wrapper = new QueryWrapper<>();
        if (ArrayUtil.isNotEmpty(productIds)) {
            wrapper.in("id", Stream.of(productIds).collect(Collectors.toList()));
        }
        wrapper.and(w -> w.isNull("keyword").or().eq("keyword", ""));
        List<WjStoreProduct> products = storeProductMapper.selectList(wrapper);

        // 更新库存
        if (CollUtil.isNotEmpty(products)) {
            products.forEach(this::updateStock);
        }
    }

    public void updateStock(WjStoreProduct product) {
        // 规格汇总
        Integer productId = product.getId();

        // 规格库存生成
        Map<String, Long> stockMap = generateStock(product.getStoreName());
        if (CollUtil.isEmpty(stockMap)) {
            return;
        }

        // 更新库存
        stockMap.forEach((suk, stock) -> {
            if (stock >= 0) {
                log.debug("更新商品{}({})，规格{}，库存{}", product.getStoreName(), productId, suk, stock);
                service.updateVegeStock(productId.longValue(), suk, stock);
            }
        });
    }

    private Map<String, Long> generateStock(String keyword) {
        Map<String, Long> map = new HashMap<>();
        if (StrUtil.isNotEmpty(keyword)) {
            // 查询上游菜品
            QueryWrapper<WjStoreProduct> storeProductQueryWrapper = new QueryWrapper<>();
            storeProductQueryWrapper.eq("keyword", keyword);
            List<WjStoreProduct> products = storeProductMapper.selectList(storeProductQueryWrapper);
            if (CollUtil.isEmpty(products)) {
                return map;
            }
            List<Integer> productIds = products.stream()
                    .map(WjStoreProduct::getId)
                    .collect(Collectors.toList());

            // 查询上游菜品报价数据
            QueryWrapper<WjProductOffer> productOfferQueryWrapper = new QueryWrapper<>();
            productOfferQueryWrapper.in("product_id", productIds);
            productOfferQueryWrapper.eq("status", 1);
            productOfferQueryWrapper.ge("(add_time * 1000 + validity_day * 24 * 60 * 60 * 1000)", System.currentTimeMillis());
            List<WjProductOffer> offers = productOfferMapper.selectList(productOfferQueryWrapper);
            if (CollUtil.isNotEmpty(offers)) {
                // 数据整理
                offers.forEach(offer -> {
                    String suk = offer.getSuk();
                    Long stock = Optional.of(offer).map(WjProductOffer::getStock).orElse(0L);
                    if (suk == null) {
                        return;
                    }
                    if (!map.containsKey(suk) || map.get(suk) < stock) {
                        map.put(suk, stock);
                    }
                });
            }
        }
        return map;
    }
}
